var util = require('../../libs/util.js');
var app = getApp();
Page({
  data: {
    isOnlyVehicleOwner:true,
    step:1,
    plate:'',
    plate_color:'蓝牌车',
    plate_color_text: ["蓝牌车", "黄牌车", "新能源车", "粤港牌"],
    vehicleLengthList: [],
    vehicleFunctionList: [],
    vehicleSourceList: [],
    vehicle_source:'加盟车辆',
    vehicleSource:1,
    img_vehicle_licence: "/images/upload-add.svg",
    img_vehicle: "/images/upload-add.svg",
    contract: "/images/upload-add.svg",
    modalName: '',
    progress: 0,
    totalBytesSent: 0,
    totalBytesExpectedToSend: 0
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onLoad: function (e) {
    var that = this;
    if(app.globalData.CO_ID){
      that.setData({
        CO_ID:app.globalData.CO_ID
      })
    }
    if(e.CO_ID){
      that.setData({
        CO_ID:e.CO_ID
      })
    }
    this.loadVehicleProperty();
  },
  onReady: function () {
    wx.hideToast()
  },
  bindPickerChange: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = this.data[item+'_text'][e.detail.value];
    this.setData(item_value);
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  plateInput: function () {
    wx.navigateTo({
      url: '/pages/plugins/pages/plate-input/plate-input'
    })
  },
  loadVehicleProperty: function () {
    wx.showLoading({
      title: '加载车辆属性...',
      mask: true
    })
    var that = this;
    util.getData("/atapi/vehicle/vehicle/property", {}, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var data = res.data.data;
        var vehicleLengthList = [], vehicleFunctionList = [], vehicleSourceList = [];
        data.forEach(function (n) {
          if (n.type == "length") {
            vehicleLengthList.push({ name: n.name, code: n.code, volume: n.remark, checked: false });
          }
          if (n.type == "function") {
            vehicleFunctionList.push({ name: n.name,code:n.code, checked: false });
          }
          if (n.type == "source") {
            vehicleSourceList.push({ name: n.name, code: n.code, checked: false });
          }
        })
        that.setData({
          vehicleLengthList: vehicleLengthList,
          vehicleFunctionList: vehicleFunctionList,
          vehicleSourceList: vehicleSourceList
        });
      }
      wx.hideLoading()
    });
  },
  chooseLocation: function (e) {
    var that = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        that.setData({
          name: res.name,
          address: res.address,
          coord: res.longitude + ',' + res.latitude
        });
        util.getData("/xypapi/map/routerCalculate/geocode", {
          latitude: res.latitude,
          longitude: res.longitude
        }, function (res, error) {
          console.log(res); console.log(error)
          if (res.data.success) {
            that.setData({
              "addressComponent.nation": res.data.component.country,
              "addressComponent.province": res.data.component.province,
              "addressComponent.city": res.data.component.city,
              "addressComponent.district": res.data.component.district,
              "addressComponent.street": res.data.component.township
            });
          }
        });
      }
    })
  },
  chooseImage: function (e) {
    var that = this;
    if(that.data.plate  == ''){
      wx.showToast({
        title: "请先填写车牌",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    wx.chooseImage({
      sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // wx.showLoading({
        //   title: '上传中...',
        //   mask:true
        // })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var item = String(e.currentTarget.id), item_value = {};
        item_value[item] = res.tempFilePaths[0];
        that.setData(item_value);
        that.setData({
          modalName: 'uploadModal',
          progress: 0,
          totalBytesSent: 0,
          totalBytesExpectedToSend: 0
        })
        that.uploadTask = wx.uploadFile({
          url: app.server + '/wechat/passport/uploadCard_vehicle',
          header:{
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'CO_ID': app.globalData.CO_ID,
            'user_id': app.globalData.user_id,
            'item': item,
            'driverId': app.globalData.role_default == 'driver'?app.globalData.driverId:'',
            'plate': that.data.plate
          },
          success: function (res) {
            var data = JSON.parse(res.data);
            if (data.success) {
              var upload_item = String(e.currentTarget.id), item_value = {};
              item_value[upload_item] = app.server + data.data[0].path;
              that.setData(item_value);
              if (data.vehicleId){
                app.globalData.vehicleId = data.vehicleId; 
                that.setData({
                  vehicleId: data.vehicleId
                })
              }
              if (data.plate) {
                that.setData({
                  plate: data.plate
                })
              }
            }
          },
          complete: function () {
            that.setData({
              modalName: ''
            })
          }
        })
        that.uploadTask.onProgressUpdate((res) => {
          that.setData({
            progress: res.progress,
            totalBytesSent: Number(res.totalBytesSent / 1000 / 1000).toFixed(3),
            totalBytesExpectedToSend: Number(res.totalBytesExpectedToSend / 1000 / 1000).toFixed(3)
          })
        })
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  submitForms: function (e) {
    var that = this;
    // try{
    //   if (!that.data.address) {
    //     wx.showToast({
    //       title: "未选择地址",
    //       image: '/images/wrong.png',
    //       duration: 2000
    //     });
    //     return false;
    //   }
    //   if (!that.data.addressComponent.province) {
    //     wx.showToast({
    //       title: "地址解析失败",
    //       image: '/images/wrong.png',
    //       duration: 2000
    //     });
    //     return false;
    //   }
    // }catch(e){};
    var data = {
      plate: that.data.plate,
      plate_color: that.data.plate_color||'',
      vehicleLength: that.data.vehicleLength,
      vehicleFunction: that.data.vehicleFunction,
      vehicleSource: that.data.vehicleSource,
      approved_load: that.data.approved_load || '',
      vehicleVolume: that.data.vehicleVolume || '',
      vehicle_spec_in: (that.data.vehicleSizeLength||0) * 1000 + 'X' + 
      (that.data.vehicleSizeWidth||0) * 1000 + 'X' + (that.data.vehicleSizeHeight||0) * 1000,
      province: that.data.addressComponent?that.data.addressComponent.province:'',
      city: that.data.addressComponent?that.data.addressComponent.city:'',
      district: that.data.addressComponent?that.data.addressComponent.district:'',
      street: that.data.addressComponent?that.data.addressComponent.street:'',
      station_address: that.data.address || '',
      station_coord: that.data.coord || '',
      img_vehicle_licence: that.data.img_vehicle_licence || '',
      vin: that.data.vin || '',
      engineno: that.data.engineno || '',
      img_vehicle: that.data.img_vehicle || '',
      vehicleId: that.data.vehicleId || '',
      user_id: app.globalData.user_id,
      CO_ID: app.globalData.CO_ID
    };
    console.log(data)
    if (!data.plate) {
      wx.showToast({
        title: "请输入车牌",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    if (!data.vehicleLength && data.vehicleLength != 0) {
      wx.showToast({
        title: "请选择车辆长度",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    if (!data.vehicleFunction && data.vehicleFunction != 0) {
      wx.showToast({
        title: "请选择车辆功能",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    if (!data.vehicleSource && data.vehicleSource != 0) {
      wx.showToast({
        title: "请选择车辆来源",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    // if (!data.approved_load) {
    //   wx.showToast({
    //     title: "请输入载重",
    //     image: '/images/wrong.png',
    //     duration: 2000
    //   });
    //   return false;
    // }
    // if (!data.vehicleVolume) {
    //   wx.showToast({
    //     title: "请输入载货空间",
    //     image: '/images/wrong.png',
    //     duration: 2000
    //   });
    //   return false;
    // }
    // if (data.img_vehicle_licence == '/images/upload-add.svg') {
    //   wx.showToast({
    //     title: "请上传行驶证",
    //     image: '/images/wrong.png',
    //     duration: 2000
    //   });
    //   return false;
    // }
    // if (data.img_vehicle == '/images/upload-add.svg') {
    //   wx.showToast({
    //     title: "请上传车辆相片",
    //     image: '/images/wrong.png',
    //     duration: 2000
    //   });
    //   return false;
    // }
    wx.showLoading({    
      title: '请稍候...',
    });
    util.putData("/wechat/passport/regVehicle", data, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: "注册成功",
          icon: "success",
          duration: 2000
        });
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      } else if (res.data.success == false) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000,
          mask: true
        });
      }
    });
  },
  showModal(e) {
    var that = this;
    that.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  vsl_Input: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    var value = e.detail.value;
    item_value[item] = value;
    this.setData(item_value);
    this.setData({
      vehicleVolume: ((Number(this.data.vehicleSizeLength) || 0) * (Number(this.data.vehicleSizeWidth) || 0) * (Number(this.data.vehicleSizeHeight) || 0)).toFixed(1)
    })
  },
  chooseCheckbox(e) {
    var that = this;
    var items = that.data.vehicleLengthList;
    var name = e.currentTarget.dataset.name;
    var item = String(e.currentTarget.dataset.id), item_value = {};
    if (item == 'vehicle_function'){
      items = that.data.vehicleFunctionList;
    }
    if (item == 'vehicle_source') {
      items = that.data.vehicleSourceList;
    }
    for (var i = 0, lenI = items.length; i < lenI; ++i) {
      if (items[i].name == name) {
        items[i].checked = !items[i].checked;
        item_value[item] = items[i].name;
        if (item == 'vehicle_function') {
          item_value['vehicleFunction'] = items[i].code;
        }
        if (item == 'vehicle_length') {
          item_value['vehicleLength'] = items[i].code;
        }
        if (item == 'vehicle_source') {
          item_value['vehicleSource'] = items[i].code;
        }
        that.setData(item_value);
      } else {
        items[i].checked = false
      }
    }
    if (item == 'vehicle_function') {
      this.setData({
        vehicleFunctionList: items
      })
    } else if (item == 'vehicle_source') {
      this.setData({
        vehicleSourceList: items
      })
    } else {
      this.setData({
        vehicleLengthList: items
      })
    }
  },
  onShow:function(){
    var that = this;
    wx.getStorage({
      key: 'plate',
      success(res) {
        that.setData({
          plate: res.data
        });
        wx.removeStorage({
          key: 'plate',
          success(res) {
            console.log(res)
          }
        })
      }
    })
  },
  backToPrev:function(){
    wx.navigateBack({
      delta: 1
    })
  }
});